package middle

import (
	"RoccBlog/api"
	"RoccBlog/global"
	"RoccBlog/model"
	"RoccBlog/util"
	"RoccBlog/util/constant"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

// Authority 登录验证
func Authority() gin.HandlerFunc {

	controller := api.BaseController{}

	return func(ctx *gin.Context) {
		token := ctx.GetHeader(constant.TokenHeaderName)

		// 没有token 下一步
		if token == "" {
			ctx.Next()
			return
		}

		// 解析token
		claims, err := util.ParseToken(fmt.Sprint(token))

		// 解析不通过
		if err != nil {
			(&controller).Response(ctx, http.StatusUnauthorized, "身份不合法!"+err.Error(), nil)
			ctx.Abort()
			return
		}

		// 获取到用户
		subject, _ := claims.GetSubject()

		key := constant.RedisLoginUserPrefix + subject + token
		log.Println("redis 存储key=", key)
		userInfo, err := global.RedisClient.Get(ctx, key).Result()
		if err != nil {
			(&controller).Response(ctx, http.StatusUnauthorized, "身份不合法!"+err.Error(), nil)
			ctx.Abort()
			return
		}

		// 延长到期时间
		err = global.RedisClient.Expire(ctx, constant.RedisLoginUserPrefix+subject+token, time.Minute*time.Duration(global.Config.Jwt.Expire)).Err()

		if err != nil {
			(&controller).Response(ctx, http.StatusUnauthorized, "身份续签失败!"+err.Error(), nil)
			ctx.Abort()
			return
		}
		var user model.User
		err = json.Unmarshal([]byte(userInfo), &user)
		if err != nil {
			log.Println(err.Error())
		}

		// 存储到请求中
		ctx.Set(constant.ContextLoginUser, user)
	}
}
